import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/mobile.dart';
import 'package:wallpaper/components/appbar_base.dart';
import 'package:wallpaper/components/images/image_load.dart';
import 'package:wallpaper/components/images/image_view.dart';
import 'package:wallpaper/model/image_base.dart';
import 'package:rxdart/rxdart.dart';
import 'package:wallpaper/model/options_base.dart';

// ignore: must_be_immutable
class MobileHome extends StatefulWidget {
  String order;
  String title;
  MobileHome({super.key, required this.order, required this.title});

  @override
  State<MobileHome> createState() => _MobilePageState();
}

class _MobilePageState extends State<MobileHome> {
  List<ImageBase> imgs = [];
  int page = 1;
  int limit = 30;
  final ScrollController _scrollController = ScrollController();
  bool isLoading = false;

  void getData() async {
    if (isLoading || !mounted) return;
    setState(() {
      isLoading = true;
    });
    Response res =
        await mobileAll(page: page, limit: limit, order: widget.order);
    if (res.data['msg'] == 'success') {
      setState(() {
        if (res.data['res'] == null) return;
        var data = res.data['res']['vertical'];
        List imgList = (data as List<dynamic>).map((item) {
          String largePath = item['preview'] ?? '';
          String smallPath = item['img'] ?? '';
          String tags = (item['tag'] as List<dynamic>?)?.join(' ') ?? '';
          return ImageBase(
            largePath: largePath,
            smallPath: smallPath,
            tags: tags,
          );
        }).toList();
        imgs.addAll(imgList as Iterable<ImageBase>);
        page++;
      });
    }
    setState(() {
      isLoading = false;
    });
  }

  // 节流函数
  final _throttle = PublishSubject<void>();
  @override
  void initState() {
    _scrollController.addListener(() {
      if (_scrollController.position.pixels >=
          _scrollController.position.maxScrollExtent - 200) {
        _throttle.add(null);
      }
    });
    _throttle.throttleTime(Duration(milliseconds: 300)).listen((_) {
      getData();
    });
    // 初始化时获取数据 等待页面渲染完成
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getData();
    });
    super.initState();
  }

  @override
  void dispose() {
    _throttle.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppbarBase(title: widget.title),
      body: RefreshIndicator(
          child: Padding(
            padding: const EdgeInsets.all(1),
            child: isLoading && imgs.isEmpty
                ? Center(child: CircularProgressIndicator())
                : GridView.builder(
                    controller: _scrollController,
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: OptionsBase().imageColumns(context),
                      childAspectRatio: 0.7,
                    ),
                    itemCount: imgs.length,
                    itemBuilder: (context, index) {
                      return buildItem(context, index);
                    },
                  ),
          ),
          onRefresh: () {
            setState(() {
              imgs.clear();
              page = 1;
            });
            getData();
            return Future.delayed(
                Duration(milliseconds: OptionsBase().refreshTime));
          }),
    );
  }

  Widget buildItem(context, int index) {
    return Container(
      margin: EdgeInsets.all(OptionsBase().padding / 2),
      decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.surface,
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
              color: Theme.of(context).colorScheme.shadow,
              offset: Offset(1, 2),
              blurRadius: 2,
            ),
          ]),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10),
        child: GestureDetector(
          onTap: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => ImageView(
                          images: imgs,
                          selectedIndex: index,
                          isMobile: true,
                          resetGetdata: () {},
                        )));
          },
          child: Stack(alignment: Alignment.bottomLeft, children: [
            SizedBox(
                width: double.infinity,
                height: double.infinity,
                child: ImageLoad(imageUrl: imgs[index].smallPath)),
            Container(
                color: const Color.fromARGB(24, 158, 158, 158),
                width: double.infinity,
                height: imgs[index].tags == "" ? 0 : 20,
                child: Padding(
                  padding: const EdgeInsets.only(left: 5, right: 5),
                  child: Text(
                    imgs[index].tags,
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                    style: TextStyle(color: Colors.white, fontSize: 13),
                  ),
                )),
          ]),
        ),
      ),
    );
  }
}
